<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Validate;
use app\common\library\Token;
/**
 * 首页接口
 */
class Curriculum extends Api
{

    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 精品课程列表
     * 
     */
    public function jcurriculum_list()
    {
        $list = Db('curriculum')->where(['status'=>'normal','statu'=>1])->select();
        foreach ($list as $key => $value) {
            $list[$key]['images'] = explode(',',$value['images']);
            $list[$key]['images'] = array_slice($list[$key]['images'],1);
        }
        if ($list) {
            $this->success('操作成功',$list);
        }else{
            $this->error('操作失败');
        }
    }

    /**
     * 课程列表
     * 
     */
    public function curriculum_list()
    {   
        $type_id = $this->request->request('type_id');
        $where = [];
        if ($type_id) {
            $where['type_id'] = $type_id;
        }
        $cert_id = $this->request->request('cert_id');
        if ($cert_id) {
            $where['cert_id'] = $cert_id;
        }
        $list = Db('curriculum')->where($where)->where(['status'=>'normal','statu'=>1])->select();
        foreach ($list as $key => $value) {
            $list[$key]['images'] = explode(',',$value['images']);
            $list[$key]['images'] = array_slice($list[$key]['images'],1);
        }
        if ($list) {
            $this->success('操作成功',$list);
        }else{
            $this->error('操作失败');
        }
    }

    /**
     * 课程详情
     * 
     */
    public function curriculum_info()
    {   
        $id = $this->request->request('id');
        $curriculum_info = Db('curriculum')->where(['id'=>$id])->find();
        $curriculum_info['images'] = explode(',',$curriculum_info['images']);
        //获取课程视频
        $curriculum_info['view'] = Db('view')->where(['curriculum_id'=>$id])->order('weigte,addtime')->select();
        
        if ($curriculum_info) {
            $this->success('操作成功',$curriculum_info);
        }else{
            $this->error('操作失败');
        }
    }

    /**
     * 报名课程
     * 
     */
    public function sign()
    {   
        $token = $this->request->request('token');
        //根据token获取用户信息
        $userid = Token::get($token);
        if ($userid==[]) {
            $this->error('请先登录');
        }
        $data = $_POST;
        if (!$data['curriculum_id']) {
            $this->error("参数错误");
        }
        
        
        if (!$data['name']) {
            $this->error("姓名不能为空");
        }
        if (!Validate::regex($data['phone'], "^1\d{10}$"))
        {
            $this->error("手机格式不正确");
        }
        //判断是否报名已满
        $curriculum = Db('curriculum')->field('id,num,yinum')->where(['id'=>$data['curriculum_id']])->find();
        if ($curriculum['num']<=$curriculum['yinum']) {
            $this->error("报名人数已满");
        }
        $data['user_id'] = $userid['user_id'];
        $data['addtime'] = time();
        unset($data['token']);
        $r = Db('sign_up')->insert($data);
        if ($r) {
            Db('curriculum')->where(['id'=>$data['curriculum_id']])->setInc('yinum');
            $this->success('报名成功');
        }else{
            $this->error("报名失败");
        }
        
    }
    /**
     * 支付课程费、、添加财务日志
     * 
     */
    public function pay(){ 
        $token = $this->request->request('token');
        //根据token获取用户信息
        $userid = Token::get($token);
        if ($userid==[]) {
            $this->error('请先登录');
        } 
        $curr_id = $this->request->request('curr_id');
        if (!$curr_id) {
            $this->error("参数错误");
        }
        //获取课程费用
        $fei = Db('curriculum')->field('title,price')->where('id',$curr_id)->find();
        // dump($fei);exit;
        //添加财务日志
        $data['user_id'] = $userid['user_id'];
        $data['curr_name'] = $fei['title'];
        $data['num'] = $fei['price'];
        $data['inout'] = 'out';
        $data['createtime'] = time();
        //添加财务日志
        $r = Db('finance_log')->insert($data);
        if ($r) {
            $this->success('支付成功');
        }else{
            $this->error("支付失败");
        }
        
    }
    /**
     * 财务日志
     * 
     */
    public function finance_log(){
        $token = $this->request->request('token');
        //根据token获取用户信息
        $userid = Token::get($token);
        if ($userid==[]) {
            $this->error('请先登录');
        }
        $list = Db('finance_log')->where('user_id',$userid['user_id'])->select();
        if ($list) {
            $this->success('获取成功',$list);
        }else{
            $this->error("获取失败");
        }
    }
    /**
     * 企业分类
     * 
     */
    public function type(){
        $pid = $this->request->request('pid');
        $list = Db('category')->field('id,name')->where(['type'=>'default','status'=>'normal','pid'=>$pid])->order('weigh desc')->select();
        if ($list) {
            $this->success('操作成功',$list);
        }else{
            $this->error('操作失败');
        }
    }
    /**
     * 证书分类
     * 
     */
    public function cert(){
        $list = Db('category')->field('id,name')->where(['type'=>'page','status'=>'normal'])->order('weigh desc')->select();
        if ($list) {
            $this->success('操作成功',$list);
        }else{
            $this->error('操作失败');
        }
    }


    /**
     * 课程习题
     * 
     */
    public function curriculum_test(){
        $token = $this->request->request('token');
        //根据token获取用户信息
        $userid = Token::get($token);
        if ($userid==[]) {
            $this->error('请先登录');
        }

        $curriculum_id = $this->request->request('curriculum_id');
        if (!$curriculum_id) {
            $this->error('参数错误');
        }
        $type = $this->request->request('type');
        if (!$type) {
            $this->error('参数错误');
        }
        //随机获取课程题目ids
        $arrtest = $this->extract_test($curriculum_id,30);
        // dump($arrtest);exit;
        $list = Db('curriculum_test')->where(['status'=>'normal','id'=>array('in',$arrtest)])->select();
        if ($list) {
            //生成试卷
            $juanid = $this->add_juan($userid['user_id'],$arrtest,$curriculum_id,$type); //返回卷子id
            // $this->success('操作成功',$list);
            return json(['code'=>1,'msg'=>'操作成功','juanid'=>$juanid,'data'=>$list]);
        }else{
            $this->error('操作失败');
        }
    }

    /**
     * 生成试卷
     * 
     */
    public function add_juan($user_id,$test_ids,$curriculum_id,$type_status){
        $data['user_id'] = $user_id;
        $data['test_ids'] = $test_ids;
        $data['curriculum_id'] = $curriculum_id;
        $data['type_status'] = $type_status;
        $data['addtime'] = time();
        $r = Db('curriculum_juan')->insertGetId($data);
        if ($r) {
            return $r;
        }else{
            $this->error('试卷获取失败');
        }
    }
    /**
     * 随机抽取课程试题
     *
     * curriculum_id 课程id
     * num 抽取题目数量
     */
    public function extract_test($curriculum_id,$num){
        //根据课程id获取课程分类
        $type_id = Db('curriculum')->where(['id'=>$curriculum_id])->value('type_id');
        //根据分类获取题目;
        $erji = Db('curriculum_test')->field('id')->where(['status'=>'normal','type_id'=>$type_id])->select();  //题目ids
        if (!$erji) {
            $this->error('暂无课程题目');
        }
        foreach ($erji as $k => $val) {
            $arr[$k]=$val['id'];   //ids转一维数组
        }
        $count = count($arr); //获取数组长度

        $num = $num;    //需要抽取的默认条数
        if($count < $num){$num = $count;}
        $i = 1;
        $ary = array();
        while($i<=$num){
            $rundnum = rand(0, $count-1);//抽取随机数
            //过滤重复 
            if(!in_array($rundnum,$ary)){
                $ary[] = $rundnum;
            }else{
                $i--;
            }
            $i++;            
        }
        foreach ($ary as $k2 => $val2) {
            $arrtest[]=$arr[$val2];          //随机抽取的题目ids
        }
        $arrtest = implode(',',$arrtest);    //转字符串
        return $arrtest;
    }

    /**
     * 做题
     *
     */
    public function do_test(){
        $token = $this->request->request('token');
        $juan_id = $this->request->request('juan_id');
        $test_id = $this->request->request('test_id');
        $result = $this->request->request('result');
        //根据token获取用户信息
        $userid = Token::get($token);
        if ($userid==[]) {
            $this->error('请先登录');
        }
        if (!$juan_id || !$test_id || !$result) {
            $this->error('参数错误');
        }
        //判断是否已做
        $find = Db('curriculum_mytest')->where(['juan_id'=>$juan_id,'test_id'=>$test_id])->find();
        if ($find) {
            //修改
            $r = Db('curriculum_mytest')->where(['juan_id'=>$juan_id,'test_id'=>$test_id])->update(['result'=>$result]);
        }else{
            //获取该提正确答案
            $true = Db('curriculum_test')->where(['id'=>$test_id])->value('true_status');
            $data['user_id'] = $userid['user_id'];
            $data['test_id'] = $test_id;
            $data['juan_id'] = $juan_id;
            $data['result'] = $result;
            $data['true_result'] = $true;
            $data['addtime'] = time();
            $r = Db('curriculum_mytest')->insert($data);
        }
        
        if ($r) {
            $this->success('操作成功');
        }else{
            $this->error('操作失败');
        }
    }

    /**
     * 答题卡
     *
     */
    public function kapian(){
        $juan_id = $this->request->request('juan_id');
        //获取该卷子的试题
        $test_ids = Db('curriculum_juan')->where(['id'=>$juan_id])->value('test_ids');
        $list = Db('curriculum_test')->field('id')->where(['id'=>array('in',$test_ids)])->select();
        foreach ($list as $key => $value) {
            //判断此题是否已做;
            $r = Db('curriculum_mytest')->where(['juan_id'=>$juan_id,'test_id'=>$value['id']])->find();
            if ($r) {
                $list[$key]['done'] = 'done';
            }else{
                $list[$key]['done'] = 'no';
            }
        }
        if ($list) {
            $this->success('操作成功',$list);
        }else{
            $this->error('操作失败');
        }
    }

    /**
     * 提交试卷
     *
     */
    public function hand(){
        $token = $this->request->request('token');
        //根据token获取用户信息
        $userid = Token::get($token);
        if ($userid==[]) {
            $this->error('请先登录');
        }

        $juan_id = $this->request->request('juan_id');
        //获取该卷子的试题和类型
        $test_ids = Db('curriculum_juan')->field('test_ids,type_status,curriculum_id')->where(['id'=>$juan_id])->find();
        //获取该试卷总题数;
        $count = count(explode(',',$test_ids['test_ids']));
        //统计做对的试题 
        $truenum = 0;
        $list = Db('curriculum_test')->where(['id'=>array('in',$test_ids['test_ids'])])->select();
        foreach ($list as $key => $value) {
            //判断此题是否正确;
            $r = Db('curriculum_mytest')->where(['juan_id'=>$juan_id,'test_id'=>$value['id']])->find();
            if ($r['result']==$value['true_status']) {
                $truenum++;
                $list[$key]['correct'] = 'true';
                $list[$key]['result'] = $r['result'];
            }else{
                $list[$key]['correct'] = 'error';
                $list[$key]['result'] = $r['result'];
            }
        }
        $errlist = [];
        foreach ($list as $key => $value) {
            if ($value['correct']=='error') {
                $errlist[] = $value;
            }
        }
        //统计分数
        $score = round($truenum/$count * 100);
        //判断是否合格
            //获取合格分数
            $pass_score = Db('config')->where('name','pass_score')->value('value');
        if ($score>=$pass_score) {
            $status = 1;
            //生成证书
            $this->add_certificate($userid['user_id'],$test_ids['curriculum_id']);
        }else{
            $status = 2;
        }
        if ($list) {
            //存储分数 
            Db('curriculum_juan')->where(['id'=>$juan_id])->update(['score'=>$score,'status'=>$status]);
            return json(['code'=>1,'score'=>$score,'type'=>$test_ids['type_status'],'status'=>$status,'msg'=>'操作成功','data'=>$list,'errlist'=>$errlist]);
        }else{
            $this->error('操作失败');
        }
    }
    /**
     * 生成证书
     * curriculum_id 课程id
     * user_id 用户id
     */
    public function add_certificate($user_id,$curriculum_id){
        $certid = Db('curriculum')->where(['id'=>$curriculum_id])->value('cert_id');//根据课程id获取证书id
        $sign_up = Db('sign_up')->where(['user_id'=>$user_id,'curriculum_id'=>$curriculum_id])->find();//根据课程id获取报名信息
        $cert = Db('category')->where(['id'=>$certid])->find();  //获取证书信息
        $data['user_id'] = $user_id;
        $data['cert_id'] = $certid;
        $data['name'] = $sign_up['name'];
        $data['idnum'] = $sign_up['id_num'];
        $data['certificatename'] = $cert['name'];   
        $data['validity'] = $cert['keywords'];     //有效期
            $pattern = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLOMNOPQRSTUVWXYZ'; 
            $key = '';
            for($i=0;$i<15;$i++)
            {   
                $key .= $pattern{mt_rand(0,61)};    //生成php随机数   
            }  
        $data['certificate_num'] = $key;
        $data['addtime'] = time();
        $r = Db('certificate')->insert($data);  //添加证书
        if (!$r) {
            $this->error('证书添加失败');
        }
    }
    /**
     * 获取收货地址信息
     *
     */
    public function address(){
        $token = $this->request->request('token');
        //根据token获取用户信息
        $userid = Token::get($token);
        if ($userid==[]) {
            $this->error('请先登录');
        }
        $curriculum_id = $this->request->request('curriculum_id');
        $list = Db('sign_up')->field('area,address,name,phone')->where(['user_id'=>$userid['user_id'],'curriculum_id'=>$curriculum_id])->find();
        if ($list) {
            $this->success('操作成功',$list);
        }else{
            $this->success('操作失败');
        }
    }
    /**
     * 确认收货地址信息
     *
     */
    public function sureaddr(){
        $token = $this->request->request('token');
        //根据token获取用户信息
        $userid = Token::get($token);
        if ($userid==[]) {
            $this->error('请先登录');
        }
        $juan_id = $this->request->request('juan_id');
        $data['address'] = $this->request->request('address');
        $data['name'] = $this->request->request('name');
        $data['phone'] = $this->request->request('phone');
        $list = Db('curriculum_juan')->where(['user_id'=>$userid['user_id'],'id'=>$juan_id])->update($data);
        if ($list) {
            $this->success('操作成功',$list);
        }else{
            $this->success('操作失败');
        }
    }

    /**
     * 证书查询
     *
     */
    public function certificate(){
        $id_num = $this->request->request('id_num');
        //根据身份证号查报名信息
        $list = Db('sign_up')->field('user_id')->where(['id_num'=>$id_num])->select();
        $erjistr = '';
        foreach ($list as $key => $value) {
            $erjistr .= implode(',',$value).',';
        }
        //去掉字符串最后一个字符
        $erjistr = substr($erjistr,0,strlen($erjistr)-1);   //用户ids
        //查询这些用户的证书
        $certificate = Db('certificate')->where('user_id','in',$erjistr)->select();
        if ($certificate) {
            $this->success('操作成功',$certificate);
        }else{
            $this->success('操作失败');
        }
    }
}
